<?php
class PixivPost
{
	public static function getMatches($string, $condition)
	{
		mb_regex_encoding('UTF-8');
		mb_ereg_search_init($string, $condition);
		$result = mb_ereg_search();
		$return = mb_ereg_search_getregs();
		array_shift($return);
		return $return;
	}
	
	public static function checkMatch($string, $condition)
	{
		mb_regex_encoding('UTF-8');
		
		mb_ereg_search_init($string, $condition);
		$result = mb_ereg_search();
		if($result)
		{
			return true;
		}
		else
		{
			return false;
		}
	}	

	public static function execute($botObj, $tweet, $action_value)
	{
		$ch = curl_init("http://www.pixiv.net/search.php?s_mode=s_tag&word=%E9%98%BF%E6%B1%82");
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_HEADER,0);  // DO NOT RETURN HTTP HEADERS
		curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);  // RETURN THE CONTENTS OF THE CALL
		$return_html = curl_exec($ch);	
		
		if(!$return_html)
		{
			$botObj->logEvent("PixivPost: No HTML!");
			$botObj->pluginResponse['notweet'] = 'true';
			return;
		}
		
		// HTML解析
		$parser = new DOMDocument();
		$html = mb_convert_encoding($return_html, 'HTML-ENTITIES', "UTF-8"); 
		@$parser->loadHTML($html);
		
		$xpathString = "//li/a";
		$xp = new DOMXPath($parser);
		$nodes = $xp->query($xpathString);
		
		$recentIllustration = false;
		$illustCount = 0;
		
		foreach($nodes as $node)
		{
			if(self::checkMatch($node->getAttribute("href"), "illust_id=(\d+)"))
			{
				list($illust_id) = self::getMatches($node->getAttribute("href"), "illust_id=(\d+)");
				$title = $node->firstChild->getAttribute("alt");
				
				$sql = "SELECT id FROM illustration WHERE id={$illust_id}";
				$result = $botObj->db->query($sql);
				
				if($result->num_rows == 0)
					$illustCount++;
				
				$sql = "INSERT IGNORE INTO illustration (id) VALUES($illust_id)";
				$botObj->db->query($sql);
				
				if(!$recentIllustration)
				{
					$recentIllustration = "【{$title}】 http://p.tl/i/$illust_id #pixivtweet\n";
				}
			}
		}
		
		if($recentIllustration)
		{
			if($illustCount > 1)
			{
				$botObj->twitter->post('statuses/update', array('status' => "私の新しいイラスト{$illustCount}枚見つけました♪最新はこのイラストです：　$recentIllustration\n"));
			}
			else
			{
				$botObj->twitter->post('statuses/update', array('status' => "私の新しいイラストを見つけました♪　$recentIllustration\n"));
			}
		}
	}
}
?>